package bjtu.cit.bookshop.controller.admin;

import bjtu.cit.bookshop.common.ErrorCode;
import bjtu.cit.bookshop.controller.BaseController;
import bjtu.cit.bookshop.entities.Book;
import bjtu.cit.bookshop.entities.Publisher;
import bjtu.cit.bookshop.service.IBookService;
import bjtu.cit.bookshop.service.IPublisherService;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by jia19 on 2015/10/11.
 */
@Controller
@RequestMapping("/admin/")
public class BookController extends BaseController {

    @Resource
    IBookService bookService = null;

    @Resource
    IPublisherService publisherService = null;


    @RequestMapping("book.do")
    public String book(HttpSession session, HttpServletRequest request, ModelMap model) {
        String loginName = checkAdminLogin(session);
        if (loginName == null) {
            return "/admin/index";
        }

        String page = request.getParameter("page");

        if (page == null) {
            page = "1";
        }
        model.addAttribute("isLogin", true);
        model.addAttribute("loginName", loginName);
        model.addAttribute("current", "book");


        List<Book> bookList = bookService.getBookList(10, (Integer.valueOf(page) - 1) * 10);
        model.addAttribute("bookList", bookList);
        int len = bookService.getBookListLength();
        model.addAttribute("totalPage", len / 10 + (len % 10 == 0?0:1));
        model.addAttribute("thisPage", page);


        return "/admin/book";
    }

    @ResponseBody
    @RequestMapping("delBook.do")
    public ErrorCode delBook(HttpSession session, HttpServletRequest request) {
        if (checkAdminLogin(session) == null) {
            return NO_AUTH;
        }
        String bookId = request.getParameter("id");
        if (bookId == null) {
            return PARA_ERROR;
        }
        try {
            this.bookService.deleteBookById(Integer.valueOf(bookId));
        } catch (Exception e) {
            e.printStackTrace();
            return PARA_ERROR;
        }
        return SUCCESS;
    }

    @RequestMapping("newBook.do")
    public String newBook(HttpSession session, HttpServletRequest request, ModelMap model) {
        String loginName = checkAdminLogin(session);
        if (loginName == null) {
            return "/admin/index";
        }
        model.addAttribute("isLogin", true);
        model.addAttribute("loginName", loginName);
        model.addAttribute("current", "book");

        List<Publisher> publisherList = publisherService.getPublisherList();
        model.addAttribute("publisherList", publisherList);

        return "/admin/newBook";
    }

    @ResponseBody
    @RequestMapping("addBook.do")
    public ErrorCode addBook(HttpSession session, HttpServletRequest request) {
        if (checkAdminLogin(session) == null) {
            return NO_AUTH;
        }
        String isbn = request.getParameter("isbn");
        String bookName = request.getParameter("bookName");
        String author = request.getParameter("author");
        String publisherid = request.getParameter("publisher");
        String publishDate = request.getParameter("publishDate");
        String price = request.getParameter("price");
        String quantity = request.getParameter("quantity");
        String place = request.getParameter("place");
        String type = request.getParameter("type");
        String content = request.getParameter("content");
        String category = request.getParameter("category");

        Book book = new Book();
        try {
            book.setIsbn(isbn);
            book.setBookname(bookName);
            book.setAuthor(author);
            book.setPublisherid(Integer.valueOf(publisherid));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(publishDate);
            book.setPubdate(date);
            book.setPrice(BigDecimal.valueOf(Float.valueOf(price)));
            book.setQuantity(Integer.valueOf(quantity));
            book.setPlace(place);
            book.setType(Integer.valueOf(type));
            book.setContent(content);
            book.setCategory(category);
        }
        catch (Exception e) {
            e.printStackTrace();
            return PARA_ERROR;
        }
        bookService.createABook(book);
        return SUCCESS;
    }

    @RequestMapping("bookEdit.do")
    public String bookEdit(HttpSession session, HttpServletRequest request, ModelMap model) {
        String loginName = checkAdminLogin(session);
        if (loginName == null) {
            return "/admin/index";
        }
        model.addAttribute("isLogin", true);
        model.addAttribute("loginName", loginName);
        model.addAttribute("current", "book");

        String id = request.getParameter("id");
        if (id == null) {
            return "admin/badParameter";
        }

        try {
            Book book = bookService.getBookById(Integer.valueOf(id));
            model.addAttribute("book", book);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            model.addAttribute("publishDate", sdf.format(book.getPubdate()));
            List<Publisher> publisherList = publisherService.getPublisherList();
            model.addAttribute("publisherList", publisherList);
        }
        catch (Exception e) {
            e.printStackTrace();
            return "admin/badParameter";
        }


        return "admin/bookEdit";
    }

    @RequestMapping("bookSave.do")
    public String bookSave(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session, HttpServletRequest request) {
        if (checkAdminLogin(session) == null) {
            return "badParameter";
        }

        String pic = null;
        if (file.getSize() != 0) {
            String path = request.getSession().getServletContext().getRealPath("/image");
            if (path == null) {
                File dir = new File(request.getSession().getServletContext().getRealPath("/") + "image");
                dir.mkdirs();
                path = request.getSession().getServletContext().getRealPath("/image");
            }

            String fileName = new Date().getTime() + file.getOriginalFilename();
            File targetFile = new File(path, fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {
                file.transferTo(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            pic = "/image/" + fileName;
        }

        String id = request.getParameter("bookId");
        String isbn = request.getParameter("isbn");
        String bookName = request.getParameter("bookName");
        String author = request.getParameter("author");
        String publisherid = request.getParameter("publisher");
        String publishDate = request.getParameter("publishDate");
        String price = request.getParameter("price");
        String quantity = request.getParameter("quantity");
        String place = request.getParameter("place");
        String type = request.getParameter("type");
        String content = request.getParameter("content");
        String category = request.getParameter("category");

        Book book = new Book();
        try {
            book.setId(Integer.valueOf(id));
            book.setIsbn(isbn);
            book.setBookname(bookName);
            book.setAuthor(author);
            book.setPublisherid(Integer.valueOf(publisherid));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(publishDate);
            book.setPubdate(date);
            book.setPrice(BigDecimal.valueOf(Float.valueOf(price)));
            book.setQuantity(Integer.valueOf(quantity));
            book.setPlace(place);
            book.setType(Integer.valueOf(type));
            book.setContent(content);
            book.setCategory(category);
            if (pic != null) {
                book.setPicture(pic);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return "badParameter";
        }
        bookService.updateBookInfo(book);
        return "redirect:/admin/book.do";
    }

}
